<?php
/**
 * DBShop 电子商务系统
 *
 * ==========================================================================
 * @link      https://www.dbshop.net/
 * @copyright 北京珑大钜商科技有限公司，并保留所有权利。
 * @license   https://www.dbshop.net/license.html License
 * ==========================================================================
 *
 * @author    静静的风 <baron@loongdom.cn>
 *
 */

namespace Shop\Validator;

use Admin\Entity\SelfLocation;
use Laminas\Validator\AbstractValidator;

class SelfLocationValidator extends AbstractValidator
{
    const PLEASE_SELECT         = 'pleaseSelect';
    const NOT_SCALAR            = 'notScalar';
    const LOCATION_NOT_EXISTS   = 'locationNotExists';

    protected $messageTemplates = [
        self::PLEASE_SELECT         => '请选择自提点',
        self::NOT_SCALAR            => '这不是一个标准输入值',
        self::LOCATION_NOT_EXISTS   => '您选择的自提点不存在'
    ];

    protected $entityManager;

    public function __construct($options = null)
    {
        if(isset($options['entityManager']))    $this->entityManager = $options['entityManager'];

        parent::__construct($options);
    }

    public function isValid($value)
    {
        if(!is_scalar($value)) {
            $this->error(self::NOT_SCALAR);
            return false;
        }

        if($value == 0) {
            $this->error(self::PLEASE_SELECT);
            return false;
        }

        $isValid = true;

        $addressInfo = $this->entityManager->getRepository(SelfLocation::class)->findOneBy(['locationId' => $value, 'locationState' => 1]);
        if($addressInfo == null) {
            $isValid = false;
            $this->error(self::LOCATION_NOT_EXISTS);
        }

        return $isValid;
    }
}